#include <QByteArray>
#include <QDate>
#include <QBitmap>
#include <QTimer>
#include <QFontMetrics>
#include <QTabWidget>
#include <QDebug>
#include <QMessageBox>

#include "stockinfo.h"

StockInfo::StockInfo(QWidget *parent) :
    QWidget(parent)
{
    resize(0,0);
//    this->setWindowState(Qt::WindowMinimized);

    m_info = "";

    createDisplayLable();
    addSelectedStock();

    m_pNetworkManager = new QNetworkAccessManager(this);
    connect(m_pNetworkManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slotReplyFinished(QNetworkReply*)));
    slotUpdate();

    setTimer();

    m_pStockSetting = new StockSetting;
}

StockInfo::~StockInfo()
{

}

void StockInfo::slotUpdate()
{
    m_pNetworkManager->get(QNetworkRequest(m_url));
}

void StockInfo::createDisplayLable()
{
    m_pLabel = new QLabel(0, Qt::ToolTip);
    m_pLabel->setGeometry(650,990,88,18);
    m_pLabel->setStyleSheet("background-color:blue");
}

void StockInfo::setTimer()
{
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(slotUpdate()));
    timer->start(1000);
}

void StockInfo::addSelectedStock()
{
    QString url = "http://hq.sinajs.cn/list=";
    url += "sz300175,sh000001";
    m_url.setUrl(url);
}

inline QString StockInfo::KeepDecimal(double org, int digit)
{
    QString tar =  QString::number(org, 'f', digit);
    return tar;
}

void StockInfo::removeInvalidCode(QStringList &stocksList)
{
    QString date = QDate::currentDate().toString("yyyy-MM-dd");
    foreach(QString str, stocksList)
    {
        if(!str.contains(date))
        {
            int index = stocksList.indexOf(str);
            stocksList.removeAt(index);
//            m_stockCodeList.removeAt(index);//////
        }
    }
}

void StockInfo::parseStocksData(QStringList stocksList, QHash<int, QStringList>& hash)
{
    int count = stocksList.count();
    for(int index = 0; index < count; index++)
    {
        QStringList infoList = stocksList.at(index).split(",");

        QString str = infoList.at(0);
        int from = str.indexOf("str_") + 6;
        QString stockCode = str.midRef(from, 6).toString();   //code
        QString stockName = str.section("\"", 1, 1);   //name

        float lastPrice = infoList.at(2).toFloat();
        float currentPrice = infoList.at(3).toFloat();
        float rise = (currentPrice - lastPrice)*100 / lastPrice;

        QString curPriceStr = KeepDecimal(currentPrice, 2);  //current price
        QString riseStr = KeepDecimal(rise, 2) + "%";   //extent percent

        QStringList stockInfoList;
        stockInfoList.append(stockCode);
        stockInfoList.append(stockName);
        stockInfoList.append(curPriceStr);
        stockInfoList.append(riseStr);

        hash.insert(index, stockInfoList);
    }
}

void StockInfo::setDisplayValue(QHash<int, QStringList>& hash)
{
    m_info.clear();
    int count = hash.count();
    for(int index = 0; index < count; index++)
    {
        QStringList infoList = hash.value(index);
        QString str = infoList.at(2) + "/" + infoList.at(3) + "\n";
        qDebug()<<"********str: "<<str;

        m_info.append(str);
    }

    qDebug()<<"***********display: "<<m_info<<"; count="<<count;
}

void StockInfo::setDisplayLabelSize(int width, int height)
{
    m_pLabel->setFixedSize(width, height);
}

QBitmap StockInfo::createDisplayMask(int count)
{
    QFont font("Times", 10, QFont::Bold);
    QFontMetrics fm(font);
    int labelLength = fm.width(m_info)+3;

    setDisplayLabelSize(labelLength, count*18);
    QLabel label(m_info);
    label.resize(labelLength,count*18);
    label.setStyleSheet("background-color:white; color:black; font:10pt hold");
    label.setAlignment(Qt::AlignLeft);
    QBitmap bmp = QBitmap::grabWidget(&label, label.rect());

    return bmp;
}

void StockInfo::slotReplyFinished(QNetworkReply* reply)
{
    //get the original stock data
    QByteArray byteData = reply->readAll();

    //split up into single stock data
    QString stockStr(byteData);
    QStringList stocksList = stockStr.split(";");

qDebug()<<"******************** stock info: "<<stockStr;

    removeInvalidCode(stocksList);

    //parse this text and get each stock data
    QHash<int, QStringList> hash;
    parseStocksData(stocksList, hash);

    //obtain display text
    setDisplayValue(hash);

    //get the mask
    int count = hash.count();
    QBitmap bmp = createDisplayMask(count);

    //show all the stock info
    m_pLabel->setMask(bmp);
    m_pLabel->raise();
    m_pLabel->show();
}

void StockInfo::keyPressEvent(QKeyEvent *keyEvent)
{

}

void StockInfo::setting()
{

    if(m_pStockSetting->isHidden())
    {
        m_pStockSetting->show();
        m_pStockSetting->raise();
    }
    else
    {
        m_pStockSetting->hide();
    }
}

void StockInfo::slotPressedHotkey(int value)
{
    qDebug()<<"============================================================:"<<value;
    setting();
}
